package com.sbs.demo.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Objects;

import com.alibaba.nacos.common.utils.StringUtils;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.sbs.demo.common.ResultCode;
import com.sbs.demo.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具类
 */
@Slf4j
public class FileUploadUtil {

    /**
     * 获取文件名的后缀
     */
    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtil.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    public static void upload(MultipartFile file, String bucket, String key) {
        CannedAccessControlList accessControl = CannedAccessControlList.PublicRead;
        AmazonS3 s3Client = SpringContextUtil.getBean(AmazonS3.class);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        metadata.setContentLength(file.getSize());
        try {
            PutObjectResult putObjectResult = s3Client.putObject(
                    new PutObjectRequest(bucket, key, file.getInputStream(), metadata)
                            .withCannedAcl(accessControl)
            );
            log.info("putObjectResult:{}", putObjectResult.toString());
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "上传失败");
        }
    }

    public static void upload(InputStream inputStream, String bucket, String key, String contentType, long size) {
        CannedAccessControlList accessControl = CannedAccessControlList.PublicRead;
        AmazonS3 s3Client = SpringContextUtil.getBean(AmazonS3.class);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);
        metadata.setContentLength(size);
        try {
            PutObjectResult putObjectResult = s3Client.putObject(
                    new PutObjectRequest(bucket, key, inputStream, metadata)
                            .withCannedAcl(accessControl)
            );
            log.info("putObjectResult:{}", putObjectResult.toString());
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "上传失败");
        }
    }

    private static String execCmd(String[] cmd) {
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            process.getErrorStream();
            int res = process.waitFor();
            LineNumberReader br = new LineNumberReader(new InputStreamReader(
                    process.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            LineNumberReader br1 = new LineNumberReader(new InputStreamReader(
                    process.getErrorStream()));
            while ((line = br1.readLine()) != null) {
                sb.append(line).append("\n");
            }
            log.info("cmd result:{}", res);
            log.info("执行命令 {}:{}", cmd, sb);
            br1.close();
            br.close();
            if (res != 0) {
                throw new ServiceException(ResultCode.OPERATION_FAILED, "ffmpeg operation failed");
            }
            return sb.toString();
        } catch (Exception e) {
            log.error("execCmdError", e);
            throw new ServiceException(ResultCode.OPERATION_FAILED, "ffmpeg operation failed");
        }
    }


}
